package com.common.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.constant.SystemConstants;
import com.common.domain.entity.*;
import com.common.domain.vo.UserInfoVo;
import com.common.domain.vo.UserVo;
import com.common.enums.AppHttpCodeEnum;
import com.common.exception.SystemException;
import com.common.mapper.UserMapper;
import com.common.service.UserService;

import com.common.util.BeanCopyUtils;
import com.common.util.SecurityUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
* @author pc
* @description 针对表【sys_user(用户表)】的数据库操作Service实现
* @createDate 2023-08-31 22:16:53
*/
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
implements UserService {
    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private UserMapper userMapper;
    @Override
    public ResponseResult register(User user) {
        //对数据进行非空判断
        if(!StringUtils.hasText(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_NOT_NULL);
        }
        if(!StringUtils.hasText(user.getPassword())){
            throw new SystemException(AppHttpCodeEnum.PASS_NOT_NULL);
        }

        //对数据是否存在进行判断
        if(!userNameExist(user.getUserName())){
            throw new SystemException(AppHttpCodeEnum.USERNAME_EXIST);
        }
        if(!nickNameExist(user.getNickName())){
            throw new SystemException(AppHttpCodeEnum.NICKNAME_EXIST);
        }

        //对密码加密操作
        String encode = passwordEncoder.encode(user.getPassword());
        user.setPassword(encode);
        //存入数据库
        save(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult userInfo() {
        //获取当前用户id
        Long userId = SecurityUtils.getUserId();
        //查询用户信息
        User user = getById(userId);
        //封装成USerInfo
        UserInfoVo userInfoVo = BeanCopyUtils.copyBean(user, UserInfoVo.class);
        //将身份证和手机号进行脱敏返回
        userInfoVo.setCardId(userInfoVo.getCardId().substring(0,5)+"*****"+userInfoVo.getCardId().substring(13));
        userInfoVo.setPhoneNumber(userInfoVo.getPhoneNumber().substring(0,3)+"****"+userInfoVo.getPhoneNumber().substring(7));
        return ResponseResult.okResult(userInfoVo);
    }

    @Override
    public ResponseResult updateUserInfo(User user) {
        user.setCardId(null);
        if(!user.getPhoneFlag()){
            user.setPhoneNumber(null);
        }
        user.setId(SecurityUtils.getUserId());
        if(updateById(user)){
            return ResponseResult.okResult();
        }
        return  ResponseResult.errorResult(AppHttpCodeEnum.SYSTEM_ERROR);
    }

    @Override
    public ResponseResult validUsername(String userName,String type) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, userName);
        queryWrapper.in(User::getType, Arrays.asList(type.split(",")));
        User user = getOne(queryWrapper);
        if(user != null){
            return ResponseResult.okResult(user.getId());
        }
        return ResponseResult.errorResult(-101,"该用户不存在");
    }

    @Override
    public ResponseResult userUpdatePassword(String oldPassword, String password) {
        //oldPassword进行加密
        String encodeOldPassword = passwordEncoder.encode(oldPassword);
        //得到原密码
        LoginUser loginUser = SecurityUtils.getLoginUser();
        String pass = loginUser.getPassword();

        if(!encodeOldPassword.equals(pass)){
            return ResponseResult.errorResult(AppHttpCodeEnum.PASSWORD_ERROR);
        }

        return null;
    }

    @Override
    public ResponseResult allUserList(Integer pageNum, Integer pageSize, String name, String className, String studentId) {
        PageHelper.startPage(pageNum,pageSize);

        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper();
        wrapper.like(StringUtils.hasText(name),User::getUserName,name);
        wrapper.like(StringUtils.hasText(className),User::getClassName,className);
        wrapper.like(StringUtils.hasText(studentId),User::getStudentId,studentId);
        wrapper.eq(User::getType, SystemConstants.USER);

        wrapper.orderByDesc(User::getCreateTime);
        List<User> list = userMapper.selectList(wrapper);

        List<UserVo> userVos = BeanCopyUtils.copyBeanList(list, UserVo.class);
        PageInfo<UserVo> pageInfo = new PageInfo<>(userVos);
        pageInfo.setList(userVos);

        return ResponseResult.okResult(pageInfo);
    }

    @Override
    public ResponseResult deleteUser(String ids) {
        String[] split = ids.split(",");
        removeByIds(Arrays.asList(split));
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult insertUser(User user) {

        String encodePassword = passwordEncoder.encode(user.getPassword());
        user.setPassword(encodePassword);
        save(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult updateUser(User user) {
        if(StringUtils.hasText(user.getPassword())) {
            String encodePassword = passwordEncoder.encode(user.getPassword());
            user.setPassword(encodePassword);
        }
        updateById(user);
        return ResponseResult.okResult();
    }

    @Override
    public ResponseResult changeStatus(Long id, String status) {
        //先找到
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper();
        wrapper.eq(User::getId,id);
        List<User> list = list(wrapper);
        //改变值
        list.get(0).setStatus(status);
        //修改
        update(list.get(0),wrapper);
        return ResponseResult.okResult();
    }

    private boolean nickNameExist(String nickName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getNickName, nickName);
        int count = count(queryWrapper);
        if(count > 0){
            return false;
        }
        return true;
    }

    private boolean userNameExist(String userName) {
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUserName, userName);
        int count = count(queryWrapper);
        if(count > 0){
            return false;
        }
        return true;
    }
}
